﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using NBlog.Web.Application.Infrastructure;
using DotNetOpenAuth.AspNet.Clients;
using NBlog.Web.Application.Service;
using System.Web;
using System.Web.Configuration;

namespace NBlog.Web.Controllers
{
    public partial class AuthenticationController : LayoutController
    {
        public AuthenticationController(IServices services) : base(services) { }

        [HttpGet]
        public ActionResult Login(string returnUrl)
        {
            var model = new LoginModel { ReturnUrl = returnUrl.AsNullIfEmpty() ?? Url.Action("Index", "Home") };
            return View(model);
        }


        [HttpGet]
        public ActionResult Logout(string returnUrl)
        {
            FormsAuthentication.SignOut();

            var url = returnUrl.AsNullIfEmpty() ?? Url.Action("Index", "Home");
            return Redirect(url);
        }

        public void SignIn()
        {
            var client = new GoogleOpenIdClient();
            string action = string.Format("http://{0}{1}", Services.Config.Current.Site, Url.Action("OAuthCallback").ToLower());
            client.RequestAuthentication(HttpContext, new Uri(action));
        }

        public ActionResult OAuthCallback(string returnUrl)
        {
            SetAuthCookie(Request["openid.ext1.value.alias1"], false, string.Empty);
            return Redirect(returnUrl.AsNullIfEmpty() ?? Url.Action("Index", "Home"));
        }

        private void SetAuthCookie(string username, bool createPersistentCookie, string userData)
        {
            if (string.IsNullOrEmpty(username))
                throw new ArgumentNullException("username");

            var authenticationConfig =
                (AuthenticationSection)WebConfigurationManager.GetWebApplicationSection("system.web/authentication");

            var timeout = (int)authenticationConfig.Forms.Timeout.TotalMinutes;
            var expiry = DateTime.Now.AddMinutes((double)timeout);

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
              username,
              DateTime.Now,
              expiry,
              createPersistentCookie,
              userData,
              FormsAuthentication.FormsCookiePath);

            string encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
            {
                Value = encryptedTicket,
                HttpOnly = true,
                Secure = authenticationConfig.Forms.RequireSSL
            };

            if (ticket.IsPersistent)
                cookie.Expires = ticket.Expiration;

            Response.Cookies.Add(cookie);
        }
    }
}
